<?php
/**
 *
 * Dual-licensed under the GNU GPL v3 and the MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright 2012, Suman (srs81 @ GitHub)
 * @package       plugin
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 *                and/or GNU GPL v3 (http://www.gnu.org/copyleft/gpl.html)
 */
 
class UploadHelper extends AppHelper {

	var $helpers = array('Html','Javascript');

        var $script_add = false;

	public function view ($model, $id, $edit=false) {
		$results = $this->listing ($model, $id);
				
		$directory = $results['directory'];
		$baseUrl = $results['baseUrl'];
		$files = $results['files'];

		$str = "<dt>" . __("Files") . "</dt>\n<dd>";
		$count = 0;
		$webroot = Router::url("/") . "ajax_multi_upload";
		foreach ($files as $file) {
			$type = pathinfo($file, PATHINFO_EXTENSION);
			$filesize = $this->format_bytes (filesize ($file));
			$f = basename($file);
			$url = $baseUrl . "/$f";
			if ($edit) {
				$baseEncFile = base64_encode ($file);
				$delUrl = "$webroot/uploads/delete/$baseEncFile/";			
				$str .= "<a href='$delUrl'><img src='" . Router::url("/") . 
					"ajax_multi_upload/img/delete.png' alt='Delete' /></a> ";
			}
			$str .= "<img src='" . Router::url("/") . "ajax_multi_upload/img/fileicons/$type.png' /> ";
			$str .= "<a href='$url'>" . $f . "</a> ($filesize)";
			$str .= "<br />\n";
		}
		$str .= "</dd>\n"; 
		return $str;
	}

	public function listing ($model, $id) {
		require_once (ROOT . DS . APP_DIR . "/Plugin/AjaxMultiUpload/Config/bootstrap.php");
		$dir = Configure::read('AMU.directory');
		if (strlen($dir) < 1) $dir = "files";

		$lastDir = $this->last_dir ($model, $id);
		$directory = WWW_ROOT . DS . $dir . DS . $lastDir;
		$baseUrl = Router::url("/") . $dir . "/" . $lastDir;
		$files = glob ("$directory/*");
		return array("baseUrl" => $baseUrl, "directory" => $directory, "files" => $files);
	}

        public function show_image($options = array()) {
        	$html = "";
                $html .= '<div id="'.$options['contain_thumb'].'">';
                if (isset($options['file']) && $options['file'] != "") {
                $html .= '<img src="'.Router::url("/").$options['file'].'" width="'.$options['width'].'" height="'.$options['height'].'" border="0">';
                } else
                if (isset($options['default']) && $options['default'] != "") {
                $html .= '<img src="'.Router::url("/").$options['default'].'" width="'.$options['width'].'" height="'.$options['height'].'" border="0">';
                }
                $html .= '</div>';
                return $html;
        }

	public function edit ($model, $id, $options = array()) {
		require_once (ROOT . DS . APP_DIR . "/Plugin/AjaxMultiUpload/Config/bootstrap.php");
		$dir = Configure::read('AMU.directory');
		if (strlen($dir) < 1) $dir = "files";

		$webroot = Router::url("/") . "ajax_multi_upload";

                $this->Html->script(array(
				'/ajax_multi_upload/js/fileuploader',
			),false);
                //$this->Html->css(array('/ajax_multi_upload/css/fileuploader'), null, array("inline"=>false));

                // Replace / with underscores for Ajax controller
		$lastDir = str_replace ("/", "___",
			$this->last_dir ($model, $id));

                if(empty($options['width'])) $options['width'] = 100;
                if(empty($options['height'])) $options['height'] = 100;
                if(empty($options['contain_thumb'])) $options['contain_thumb'] = 'thumb'.$lastDir;
                $str = "<div class='form-input-des'>";
                if ($options['inline'] == 1) {
                $str .= $this->show_image($options);
                }
		$str .= <<<END
			<div id="AjaxMultiUpload$lastDir" class="AjaxMultiUpload$lastDir" name="AjaxMultiUpload">
				<noscript>
					 <p>Please enable JavaScript to use file uploader.</p>
				</noscript>
			</div>

END;
                $str .= "</div>";
		return $str;
	}

	// The "last mile" of the directory path for where the files get uploaded
	function last_dir ($model, $id) {
		return $model . "/" . $id;
	}

	// From http://php.net/manual/en/function.filesize.php
	function format_bytes($size) {
		$units = array(' B', ' KB', ' MB', ' GB', ' TB');
		for ($i = 0; $size >= 1024 && $i < 4; $i++) $size /= 1024;
		return round($size, 2).$units[$i];
	}
}
